using System;
using PhillyCodeCamp.DTO;
using PhillyCodeCamp.Infrastructure;
using PhillyCodeCamp.Services;

namespace PhillyCodeCamp.UI
{
    public class TaxCalculatorPresenter : PresenterBase
    {
        private readonly ITaxCalculatorView _taxCalculatorView;
        private readonly ITaxService _taxService;
        private readonly IValidationService _validationService;

        public TaxCalculatorPresenter(ITaxCalculatorView taxCalculatorView)
            : this(
            taxCalculatorView,
            DependencyResolver.Resolve<ITaxService>(), 
            DependencyResolver.Resolve<IValidationService>())
        {
            
        }
        public TaxCalculatorPresenter(
            ITaxCalculatorView taxCalculatorView, 
            ITaxService taxService,
            IValidationService validationService)
        {
            _taxCalculatorView = taxCalculatorView;
            _taxService = taxService;
            _validationService = validationService;
        }

        public override void OnViewInitialized()
        {
            _taxCalculatorView.States =  _taxService.GetListOfStates();
        }

        public void ComputeTax()
        {
            var taxDataDTO = MapFrom(_taxCalculatorView);

            _taxCalculatorView.CalculatedTax = string.Empty;
            var brokenRules = _validationService.Validate(taxDataDTO);
            if (brokenRules.Count == 0)
            {
                _taxCalculatorView.CalculatedTax = _taxService.ComputeTax(taxDataDTO).ToString("$#.##");
            }
            else
            {
                _taxCalculatorView.ShowErrors(brokenRules.Messages);

            }
        }

        private TaxDataDTO MapFrom (ITaxCalculatorView view)
        {
            var taxDataDTO = new TaxDataDTO(
                view.Date,
                view.StateSelected,
                view.TotalIncome, view.IsBailedOut);

            return taxDataDTO;
        }
    }
}